<?php
require 'SparqlResult.php';
/**
 * Description of SparqlClient
 *
 * @author Guillaume Sainthillier
 */
class SparqlClient {

    public function __construct($ip = '127.0.0.1', $port = 3030, $point = 'space') {
        $this->endpoint = $ip.':'.$port.'/'.$point;
    }

    public function query($query) {
        $finalQuery = '
            PREFIX :            <http://ontologies.alwaysdata.net/space#>
            PREFIX instance:    <http://www.irit.fr/recherches/MELODI/ontologies/FilmographieV1.owl#>
            PREFIX rdf:         <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            PREFIX rdfs:        <http://www.w3.org/2000/01/rdf-schema#>
            PREFIX owl:         <http://www.w3.org/2002/07/owl#>
            PREFIX xsd:         <http://www.w3.org/2001/XMLSchema#>
            PREFIX fn:          <http://www.w3.org/2005/xpath-functions#>
        ' . $query;

        $params = array(
            'query' => $finalQuery,
            'output' => 'json'
        ); 
        
        $sparqlresult= array();
        
        $response   = $this->get($this->endpoint.'/query', $params);
        $results    = json_decode($response);
        
        if($results) {
            foreach($results->results->bindings as $result){
                $sparqlresult[] = new SparqlResult($result);
            }
        }
        
        return $sparqlresult;
    }

    /**
     * Send a GET requst using cURL 
     * @param string $url to request 
     * @param array $get values to send 
     * @param array $options for cURL 
     * @return string 
     */
    private function get($url, array $get = NULL, array $options = array()) {
        $defaults = array(
            CURLOPT_URL => $url . (strpos($url, '?') === FALSE ? '?' : '') . http_build_query($get),
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_TIMEOUT => 4
        );

        $ch = curl_init();
        curl_setopt_array($ch, ($options + $defaults));
        if (!$result = curl_exec($ch)) {
            trigger_error(curl_error($ch));
        }
        curl_close($ch);
        
        return $result;
    }

}
